<template>
  <div class="app-container">
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="分类">
        <el-cascader
            :props="categoryProps"
            v-model="queryCategoryIdList"
            @change="handleCategoryChange"
            style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            v-model="queryParams.brandId"
            class="m-2"
            placeholder="选择品牌"
            size="small"
            style="width: 100%"
        >
          <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" id="reset-all" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="showEdit"
            @click="handleUpdate('')"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="showDelete"
            @click="handleDelete('')"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="categoryBrandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="分类名称" prop="categoryName"/>
      <el-table-column label="品牌名称" prop="brandName"/>
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50"/>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryBrandRef" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="分类" prop="categoryIdList">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
              v-model="form.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
          >
            <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CategoryBrand">
import {
  list,
  addCategoryBrand,
  getCategoryBrandDetailInfo,
  updateCategoryBrand,
  deleteCategoryBrand
} from "@/api/product/categoryBrand.js"
import {getBrandAll} from "@/api/product/brand.js"
import {getCategoryById} from "@/api/product/category.js"
import {getCurrentInstance, ref} from "vue";
// ================数据模型定义  start ===============================================

// 定义搜索表单数据模型
const brandList = ref([])
const {proxy} = getCurrentInstance()
const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) { // 加载数据的方法
    if (typeof node.value == 'undefined') node.value = 0
    const {code, data, message} = await getCategoryById(node.value)
    data.forEach(item => {
      item.leaf = !item.hasChildren
    })
    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)
// 定义表格数据模型
const categoryBrandList = ref([])
//给后端的json对象
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    categoryId: null,
    brandId: null
  },
  form: {},
  rules: {
    categoryIdList: [
      {required: true, message: "分类不能为空", trigger: "blur"}
    ],
    brandId: [
      {required: true, message: "品牌不能为空", trigger: "blur"}
    ]
  }
})
const {queryParams, form, rules} = toRefs(data)
// 分页条数据模型
const total = ref(0)

//请求页面分页数据
function getList() {
  list(queryParams.value).then(res => {
    categoryBrandList.value = res.rows
    total.value = res.total
  })
}

getList()

//请求所有品牌数据
function getAllBrandList() {
  getBrandAll().then(res => {
    brandList.value = res.data
  })
}

getAllBrandList()
//定义收集分类id列表
const queryCategoryIdList = ref([])
const handleCategoryChange = () => {

  queryParams.value.categoryId = queryCategoryIdList.value[2]

}
//搜索按钮
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

//重置按钮
function resetQuery() {
  queryCategoryIdList.value = []
  proxy.resetForm("queryRef");
  queryParams.value.categoryId = null
  queryParams.value.brandId = null
  handleQuery();
}

const open = ref(false)
const title = ref("添加分类品牌信息")

// 表单重置
function reset() {
  form.value = {
    id: null,
    brandId: null,
    categoryId: null,
    categoryIdList: []
  };
  proxy.resetForm("categoryBrandRef");
}

//新增按钮
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加分类品牌信息"
}

function submitForm() {
  proxy.$refs['categoryBrandRef'].validate((valid) => {
    if (valid) {
      form.value.categoryId = form.value.categoryIdList[2]
      if (form.value.id != null) {
        updateCategoryBrand(form.value).then(res => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCategoryBrand(form.value).then(res => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

//取消按钮
function cancel() {
  open.value = false
  reset()
}

const ids = ref([]);
let showDelete = ref(true)
let showEdit = ref(true)

//修改回显
function handleUpdate(id) {
  const _ids = id || ids.value
  getCategoryBrandDetailInfo(_ids).then(res => {
    reset()
    title.value = "修改分类品牌信息"
    open.value = true
    form.value = res.data
  })
}

//批量操作
function handleSelectionChange(val) {
  ids.value = val.map(item => item.id)
  form.value.id = ids.value[0];
  showEdit.value = val.length != 1
  showDelete.value = !val.length
}

//删除
function handleDelete(id) {
  const _ids = id || ids.value
  proxy.$modal.confirm('是否确认删除分类品牌编号为"' + _ids + '"的数据项？').then(function () {
    return deleteCategoryBrand(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  })

}

// =========   数据模型定义 end======================================================================
</script>